from docx import Document
import re
from collections import defaultdict

def fix_figure_numbers(input_path, output_path, heading_style='Heading 1'):
    # 正则表达式匹配图片编号格式（如 "图 1-2"）
    figure_pattern = re.compile(r'(图\s*)(\d+)-(\d+)')

    doc = Document(input_path)
    current_chapter = -1  # 当前章节号，初始为0
    chapters = defaultdict(list)

    for para in doc.paragraphs:
        # 判断是否为章节标题（通过样式）
        if para.style.name == heading_style:
            current_chapter += 1  # 章节号递增
            continue

        # 判断是否为图片编号段落
        figure_match = figure_pattern.search(para.text)
        if figure_match:
            # 确定章节号：若未检测到章节标题，默认为1章
            chapter_num = current_chapter or 1

            chapters[chapter_num].append({
                'para': para,
                'original_text': para.text,
                'original_chapter': int(figure_match.group(2)),
                'original_number': int(figure_match.group(3))
            })

    # 重新生成图片编号
    for chapter_num, fig_list in chapters.items():
        for index, fig_info in enumerate(fig_list, 1):
            new_number = f"{chapter_num}-{index}"
            new_text = figure_pattern.sub(
                f"图 {new_number}", 
                fig_info['original_text']
            )
            fig_info['para'].text = new_text  # 更新段落内容

    doc.save(output_path)

# 使用示例
fix_figure_numbers(r"D:\d\doc\csdb\test.docx", 'output.docx', heading_style='Heading 1')